//
//  WYWAudioDownLoader.m
//  WYWPlayer
//
//  Created by Mr.Run on 2017/11/10.
//  Copyright © 2017年 Mr.Run. All rights reserved.
//

#import "WYWAudioDownLoader.h"
#import "WYWRemoteAudioFile.h"

@interface WYWAudioDownLoader ()<NSURLSessionDataDelegate>

@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSOutputStream *outputStream;

@property (nonatomic,strong) NSURL *url;

@end

@implementation WYWAudioDownLoader

- (NSURLSession *)session{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
}

-(void)downLoadWith:(NSURL *)url offset:(long long)offset{
    [self cancelAndCleanWithURL:url];
    self.offset = offset;
//    self.url = url;
    NSLog(@"%s~~~%d~~~%@",__func__,__LINE__,url);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:0];
    [request setValue:[NSString stringWithFormat:@"bytes=%lld-", offset] forHTTPHeaderField:@"Range"];
    NSURLSessionDataTask *task = [self.session dataTaskWithRequest:request];
    [task resume];
    
}

-(void)cancelAndCleanWithURL:(NSURL *)url{
    [self.session invalidateAndCancel];
    self.session = nil;
    [WYWRemoteAudioFile clearTmpFile:url];
    self.loadedSize = 0;
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
    
    self.totalSize = [response.allHeaderFields[@"Content-Length"] longLongValue];
    NSString *contentRangeStr = response.allHeaderFields[@"Content-Range"];
    if (contentRangeStr.length != 0) {
        self.totalSize = [[contentRangeStr componentsSeparatedByString:@"/"].lastObject longLongValue];
    }
    self.mineType = response.MIMEType;
    NSLog(@"%s~~~%d~~~%@",__func__,__LINE__,response.URL);
    self.outputStream = [NSOutputStream outputStreamToFileAtPath:[WYWRemoteAudioFile tmpFilePath:response.URL] append:YES];
    [self.outputStream open];
    completionHandler(NSURLSessionResponseAllow);
}

-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
    self.loadedSize += data.length;
//    NSLog(@"%s~~~%d~~~%zd",__func__,__LINE__,self.loadedSize);
    [self.outputStream write:data.bytes maxLength:data.length];
    
    if ([self.delegate respondsToSelector:@selector(downLoading)]) {
        [self.delegate downLoading];
    }
    
}

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
    
    if (error == nil) {
        NSURL *url = task.response.URL;
        if ([WYWRemoteAudioFile tmpFileSize:url] == self.totalSize) {
            [WYWRemoteAudioFile moveTmpPathToCachePath:url];
        }
    }
    
}

@end
